package cn.org.donald.framework.util;

import cn.org.donald.framework.constant.EncodeConstant;
import cn.org.donald.framework.constant.InfoConstant;
import cn.org.donald.framework.handler.ServiceException;
import cn.org.donald.framework.property.SmsProperties;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * @author : Donald
 * @since : 2020/11/16 17:19
 */
@Component
@SuppressWarnings("unchecked")
public class SendMsgUtil {

    @Autowired
    private SmsProperties smsProperties;

    private static Logger logger = LoggerFactory.getLogger(SendMsgUtil.class);

    private static String serverIp;
    private static String serverPort;
    private static String accountSid;
    private static String accountToken;
    private static String appId;
    private static String templateId;

    @Bean
    private void setProperties(){
        serverIp = smsProperties.getServerIp();
        serverPort = smsProperties.getServerPort();
        accountSid = smsProperties.getAccountSid();
        accountToken = smsProperties.getAccountToken();
        appId = smsProperties.getAppId();
        templateId = smsProperties.getTemplateId();
    }

    /**
     * 发送手机验证码
     * @param userId 用户id
     * @param targetPhone 目标手机号
     * @param timeout 验证码有效时间(单位秒)
     * @return 获取验证码的手机验证码token
     */
    public static String sendPhoneVerify(Long userId, String targetPhone, Integer timeout){

        String token = JwtUtil.getToken(userId+"",timeout);

        int code = (int)((Math.random()*9+1)*100000);
        String[] strings = {code + "",timeout+""};
        boolean b = sendMessage(targetPhone, templateId, strings);
        if (b){
            redisTemplate().opsForValue().set(token,code,timeout, TimeUnit.MINUTES);
            return token;
        }
        throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), InfoConstant.INTERNAL_SERVER_ERROR);

    }


    /**
     * 发送手机短信
     * @param targetPhone 目标手机号
     * @param templateId 模板id,查看容联云通讯个人信息
     * @param templateContext 根据模板填写模板字符串数组
     * @return boolean
     */
    public static boolean sendMessage(String targetPhone,String templateId,String[] templateContext){

        // TODO 发送短信

        try {
            if (StringUtil.isEmpty(targetPhone)||targetPhone.matches(EncodeConstant.VERIFY_PHONE)){
                throw new IllegalAccessException("target phone is Illegal");
            }
            CCPRestSmsSDK ccpRestSmsSDK = new CCPRestSmsSDK();
            ccpRestSmsSDK.init(serverIp,serverPort);
            ccpRestSmsSDK.setAccount(accountSid,accountToken);
            ccpRestSmsSDK.setAppId(appId);
            HashMap<String, Object> result = ccpRestSmsSDK.sendTemplateSMS(targetPhone, templateId,templateContext );
            if ("000000".equals(result.get("statusCode"))){
                logger.info("Message sent to target, the first template's context is {}; the result is {}",templateContext[0],result.toString());
                return true;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发送邮件
     * @return
     */
    public static String sendEmail( ){
        return "";
    }

    public static RedisTemplate redisTemplate(){
        return (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
    }
}
